package com.kede.app.service.impl;

import com.kede.app.domain.StoreUserOrder;
import com.kede.app.domain.Users;
import com.kede.app.domain.ZhiUserCertified;
import com.kede.app.repository.StoreUserOrderRepository;
import com.kede.app.repository.UsersRepository;
import com.kede.app.repository.ZhiUserCertifiedRepository;
import com.kede.app.service.StoreUserOrderService;
import com.kede.app.service.dto.StoreUserOrderDto;
import com.kede.app.service.dto.StoreUserOrderQueryCriteria;
import com.kede.app.service.mapstruct.StoreUserOrderMapper;
import com.kede.utils.FileUtil;
import com.kede.utils.PageUtil;
import com.kede.utils.QueryHelp;
import com.kede.utils.ValidationUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

/**
* @description 服务实现
* @author Pr.li
* @date 2023-06-10
**/
@Service
@RequiredArgsConstructor
public class StoreUserOrderServiceImpl implements StoreUserOrderService {

    private final StoreUserOrderRepository storeUserOrderRepository;
    private final StoreUserOrderMapper storeUserOrderMapper;
    private final ZhiUserCertifiedRepository zhiUserCertifiedRepository;
    private final UsersRepository usersRepository;

    @Override
    public Map<String,Object> queryAll(StoreUserOrderQueryCriteria criteria, Pageable pageable){
        Page<StoreUserOrder> page = storeUserOrderRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
        page.getContent().forEach(storeUserOrder -> {
            Users user = usersRepository.getById(storeUserOrder.getUserId());
            ZhiUserCertified store = zhiUserCertifiedRepository.findByUserId(storeUserOrder.getStoreId());
            storeUserOrder.setUsers(user);
            storeUserOrder.setStore(store);
        });
        return PageUtil.toPage(page.map(storeUserOrderMapper::toDto));
    }

    @Override
    public List<StoreUserOrderDto> queryAll(StoreUserOrderQueryCriteria criteria){
        return storeUserOrderMapper.toDto(storeUserOrderRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
    }

    @Override
    @Transactional
    public StoreUserOrderDto findById(Integer id) {
        StoreUserOrder storeUserOrder = storeUserOrderRepository.findById(id).orElseGet(StoreUserOrder::new);
        ValidationUtil.isNull(storeUserOrder.getId(),"StoreUserOrder","id",id);
        return storeUserOrderMapper.toDto(storeUserOrder);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public StoreUserOrderDto create(StoreUserOrder resources) {
        return storeUserOrderMapper.toDto(storeUserOrderRepository.save(resources));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void update(StoreUserOrder resources) {
        StoreUserOrder storeUserOrder = storeUserOrderRepository.findById(resources.getId()).orElseGet(StoreUserOrder::new);
        ValidationUtil.isNull( storeUserOrder.getId(),"StoreUserOrder","id",resources.getId());
        storeUserOrder.copy(resources);
        storeUserOrderRepository.save(storeUserOrder);
    }

    @Override
    public void deleteAll(Integer[] ids) {
        for (Integer id : ids) {
            storeUserOrderRepository.deleteById(id);
        }
    }

    @Override
    public void download(List<StoreUserOrderDto> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (StoreUserOrderDto storeUserOrder : all) {
            Map<String,Object> map = new LinkedHashMap<>();
            map.put("门店id", storeUserOrder.getStoreId());
            map.put("用户id", storeUserOrder.getUserId());
            map.put("消费数量", storeUserOrder.getNum());
            map.put("物资id", storeUserOrder.getSupplieId());
            map.put("状态：1 门店待确认 2 待领取 3 已完成", storeUserOrder.getStatus());
            map.put(" createTime",  storeUserOrder.getCreateTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }


    /**
     * 获取某个物资已经兑换的数量
     * @param supplieId
     * @return
     */
    @Override
    public Integer getStoreUserOrderNum(Integer supplieId){
        StoreUserOrder storeUserOrder = new StoreUserOrder();
        storeUserOrder.setSupplieId(supplieId);
        storeUserOrder.setStatus(5);
        List<StoreUserOrder> all = storeUserOrderRepository.findAll(Example.of(storeUserOrder));
        int i = all.stream().map(StoreUserOrder::getNum).reduce(0, (pre, next) -> {
            return pre + next;
        }).intValue();
        return i;
    }
}